// This file is a part of Funky C++.
// Copyright (C) 2011  Valentin David
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
#ifndef MIX_HH
# define MIX_HH

# include "signal.hh"

namespace funky {
  template <typename Signal>
  struct signal_mix {
    typedef typename signal_traits<Signal>::sample sample;
    typedef typename signal_traits<Signal>::duration duration;
    Signal signal;
  public:
    explicit signal_mix(Signal&& s):
      signal(std::move(s)) {}

    explicit signal_mix(const Signal& s):
      signal(s) {}

    signal_mix(signal_mix&& other)
      : signal(std::move(other.signal)) {}

    signal_mix(const signal_mix&) = default;

    signal_mix& operator=(const signal_mix& other) {
      return *this = signal_mix(other);
    }

    signal_mix& operator=(signal_mix&& other) {
      std::swap(signal, other.signal);
      return *this;
    }

    signal_mix& operator+=(const duration& d) {
      signal += d;
      return *this;
    }

    typename sample::sample
    operator*() const {
      sample r = *signal;
      typename sample::sample ret = typename sample::sample();
      for (size_t n = 0; n < sample::size; ++n) {
	ret += r[n];
      }
      return ret;
    }
  };

  template <typename Signal>
  struct signal_traits<signal_mix<Signal> > {
    typedef typename signal_traits<Signal>::sample::sample sample;
    typedef typename signal_traits<Signal>::duration duration;
  };

  template <typename T, typename RT = typename std::decay<T>::type,
	    typename = typename signal_traits<RT>::sample>
  signal_mix<RT> mix(T&& t) {
    return signal_mix<RT>{ std::forward<T>(t) };
  }

}

#endif
